package com.wft.design.oauth.service.impl;

import com.wft.design.common.security.bean.Authentication;
import com.wft.design.oauth.constant.GrantType;
import com.wft.design.oauth.entity.OauthAccount;
import com.wft.design.oauth.entity.OauthClient;
import com.wft.design.oauth.entity.OauthParameter;
import com.wft.design.oauth.service.OauthAccountService;
import com.wft.design.oauth.service.OauthClientService;
import com.wft.design.oauth.service.GrantModeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;

/**
 * @author WFT
 * @date 2019/12/20
 * description: 密码模式策略
 */
@Service
@RequiredArgsConstructor
public class PasswordModeServiceImpl implements GrantModeService {

    private final OauthClientService clientService;
    private final OauthAccountService accountService;

    @Override
    public String getName() {
        return GrantType.password.toString();
    }

    @Override
    public Authentication checking(OauthParameter parameter) {
        Assert.hasText(parameter.getUsername(),"用户名不能为空");
        Assert.hasText(parameter.getPassword(),"密码不能为空");
        Assert.hasText(parameter.getSalt(),"随机盐不能为空");
        //  获取账号信息
        OauthAccount account = this.accountService.selectByName(parameter.getUsername());
        Assert.notNull(account,"用户名不存在");
        Assert.isTrue(account.getLockFlag() == 0,"账号被锁定,请与管理员联系");
        //  校验密码
        String cipherText = this.accountService.encryption(account.getPassword(),parameter.getSalt());
        Assert.isTrue(cipherText.equals(parameter.getPassword()),"用户名或密码错误");
        //  校验客户端Id与密钥
        OauthClient client = this.clientService.selectById(parameter.getClientId());
        Assert.isTrue(this.getName().equals(client.getGrantType()),"当前客户端不支持密码模式");
        Assert.isTrue(client.getSecret().equals(parameter.getClientSecret()),"客户端密钥不正确");
        //  TODO 待实现,获取用户的权限列表
        //  返回凭证信息
        return new Authentication(account.getId(),new ArrayList<>(0));
    }
}
